package ExpressFour;

import java.io.*;
import java.util.LinkedList;

public class MyFile extends INode {
    final static String type="file";
    private String path;//如果是文件，需要路径

    private final LinkedList<String>list;//用来存储文件内容

    public MyFile(String name, long Inode, String time,String path) {
        super(name, Inode, time,type);
        this.path=path;
        list=new LinkedList<>();
    }
    //获取文件路径
    public String getPath() {
        return path;
    }
    //添加到文件
    void addToFile(String str){
        list.add(str);
    }
    //获取文件内容
    String getFile(){
        //获取文件内容
        readFromFile(path);//进行读文件

        //准备返回文件
        StringBuilder str= new StringBuilder();
        for(String str1:list){
            str.append(str1).append("\n");
        }
        return str.toString();
    }

    public void setPath(String path) {
        this.path = path;
    }

    //刷新文件信息
    void flush(){
        writeToFile(path);
    }
    //写文件
    void writeToFile(String fileName){
        try {
            File writeName = new File(fileName);
            if(writeName.exists()) {
                writeName.delete();
                writeName.createNewFile();
            }
            try (FileWriter writer = new FileWriter(writeName);
                 BufferedWriter out = new BufferedWriter(writer)
            ) {
                for(int i=0;i<list.size()-1;i++) {
                    out.write(list.get(i)+"\n");
                }
                out.write(list.get(list.size()-1));
                out.flush();
            }
        } catch (IOException e) {
            System.out.println("错误");
        }
    }
    //读文件
    void readFromFile(String fileName){
        list.clear();
        try(FileReader reader=new FileReader(fileName);
            BufferedReader br=new BufferedReader(reader)){
            String line;
            while((line=br.readLine())!=null){
                list.add(line);
            }
        }catch (IOException e){
            System.out.println("错误");
        }
    }

}
